﻿using System;
using System.Web;
using log4net;
using MyLib.IO;
using MyLib.Web;

namespace MyLib.Web.HttpHandlers {
	/// <summary>
	/// 
	/// </summary>
	public class ImageHandler : BaseFileHandler {
		/// <summary>
		/// Internal logger.
		/// </summary>
		private ILog m_logger = LogManager.GetLogger(typeof(ImageHandler));

		/// <summary>
		/// 
		/// </summary>
		private static byte[] m_blankImage = new byte[] {
			0x47, 0x49, 0x46, 0x38, 0x39, 0x61, 0x20, 0x00, 0x20, 0x00, 0x70, 0x00, 0x00, 0x21, 0xf9, 0x04, 
			0x09, 0x00, 0x00, 0x00, 0x00, 0x2c, 0x00, 0x00, 0x00, 0x00, 0x20, 0x00, 0x20, 0x00, 0x80, 0x00, 
			0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x1e, 0x84, 0x8f, 0xa9, 0xcb, 0xed, 0x0f, 0xa3, 0x9c, 0xb4, 
			0xda, 0x8b, 0xb3, 0xde, 0xbc, 0xfb, 0x0f, 0x86, 0xe2, 0x48, 0x96, 0xe6, 0x89, 0xa6, 0xea, 0xca, 
			0xb6, 0xee, 0x0b, 0x9b, 0x05, 0x00, 0x3b
		};

		/// <summary>
		/// 
		/// </summary>
		/// <param name="context"></param>
		/// <param name="fileObject"></param>
		/// <param name="fileContent"></param>
		protected override void WriteResponse(HttpContext context, FileObject fileObject, byte[] fileContent) {
			if (fileObject == null) {
				context.WriteFile("empty.gif", m_blankImage.Length,
					(s) => {
						s.Write(m_blankImage, 0, m_blankImage.Length);
					});
			} else {
				context.WriteFile(fileObject.Name, fileObject.Size,
					(s) => {
						s.Write(fileContent, 0, fileContent.Length);
					});
			}
		}
	} // end of ImageHandler.
}
